package com.snail.auth.action;

import com.alibaba.fastjson.JSON;
import com.common.ResultUtil;
import com.common.entity.BaseController;
import com.snail.auth.entity.AuthAuthority;
import com.snail.auth.entity.AuthMenu;
import com.snail.auth.service.AuthAuthorityService;
import com.snail.auth.service.AuthMenuService;
import com.snail.auth.service.AuthRoleService;
import com.snail.auth.service.AuthUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Auther: houyanfeng 2018/12/5
 * @Description:
 */
@Api(description = "权限管理", tags = {"manage auth 3 authority"})
@RestController
@RequestMapping("auth/authority")
public class AuthAuthorityController extends BaseController {
    @Autowired
    private AuthAuthorityService authorityService;
    @Autowired
    private AuthRoleService roleService;
    @Autowired
    private AuthMenuService menuService;
    @Autowired
    private AuthUserService userService;

    @ApiOperation("查看指定菜单的权限信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "menuId", value = "菜单ID", required = true, dataType = "long", paramType = "path")
    })
    @GetMapping("/{menuId}")
    public Map<String, Object> list(@PathVariable Long menuId) {
        List<AuthAuthority> list = authorityService.getByMenuId(menuId);
        return ResultUtil.result(list);
    }

    @ApiOperation("删除指定权限信息")
    @DeleteMapping(value = "/{id}")
    public Map del(@PathVariable Long id) {
        authorityService.del(id);
        return ResultUtil.result();
    }

    @GetMapping(value = "/one/{authId}")
    public Map<String, Object> detail(@PathVariable Long authId) {
        AuthAuthority auth = authorityService.getByKey(authId);
        AuthMenu menu = menuService.getByKey(auth.getMenuId());
        Map<String, Object> result = (Map<String, Object>) JSON.parse(JSON.toJSONString(auth));
        result.put("menuName", menu.getName());
        return ResultUtil.result(result);
    }

    @GetMapping(value = "/role/{roleId}")
    public Map<String, Object> queryAuthority(@PathVariable Long roleId) {
        List list = authorityService.getByRole(roleId);
        return ResultUtil.result(list);
    }

    @PostMapping
    public Map<String, Object> save(AuthAuthority entity) {
        if (!entity.getValue().startsWith(entity.getMenuId() + "_")) {
            entity.setValue(entity.getMenuId() + "_" + entity.getValue());
        }
        authorityService.save(entity);
        return ResultUtil.result();
    }

    @ApiOperation(value = "完整菜单权限结构树")
    @GetMapping("/tree")
    public Map<String, Object> tree() {
        return ResultUtil.result(authorityService.treeData());
    }
}
